﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RelationshipsDataEditor.cs" company="Vizioz Limited">
//   Open Source - MIT License 2011
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System.Web.UI;

[assembly: WebResource("Vizioz.Relationships.css.flags16.css", "text/css", PerformSubstitution = true)]
[assembly: WebResource("Vizioz.Relationships.images.flags16.png", "image/png")]

namespace Vizioz.Relationships
{
    using System;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI.WebControls;

    using ClientDependency.Core;

    using umbraco.cms.businesslogic.relation;
    using umbraco.interfaces;

    using umbraco.uicontrols.TreePicker;

    /// <summary>
    /// The relationships data editor.
    /// </summary>
    public class RelationshipsDataEditor : UpdatePanel, IDataEditor
    {
        #region Constants and Fields

        /// <summary>
        /// The _data.
        /// </summary>
        private readonly IData data;

        /// <summary>
        /// The relationships.
        /// </summary>
        private readonly string relationships;

        /// <summary>
        /// Content Picker
        /// </summary>
        private SimpleContentPicker contentPicker;

        /// <summary>
        /// Content Picker
        /// </summary>
        private Label pickerContainer;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="RelationshipsDataEditor"/> class.
        /// </summary>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        public RelationshipsDataEditor(IData data, string configuration)
        {
            this.data = data;

            this.relationships = configuration.Length > 0 ? configuration : "1";
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets Editor.
        /// </summary>
        public Control Editor
        {
            get
            {
                return this;
            }
        }

        /// <summary>
        /// Gets a value indicating whether ShowLabel.
        /// </summary>
        public bool ShowLabel
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Gets a value indicating whether TreatAsRichTextEditor.
        /// </summary>
        public virtual bool TreatAsRichTextEditor
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// Gets the Id of the current node (if found on the querystring id value)
        /// </summary>
        private static int CurrentDocId
        {
            get
            {
                var localCurrentDocId = -1; // Unknown

                int.TryParse(HttpContext.Current.Request.QueryString["id"], out localCurrentDocId);

                return localCurrentDocId;
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// The Super save.
        /// </summary>
        public void Save()
        {
        }

        /// <summary>
        /// The Super save.
        /// </summary>
        public void SuperSave()
        {
            var documentId = CurrentDocId;
            var regexId = new Regex("document_picker_(?<id>[0-9]+)_ContentIdValue", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);

            foreach (var key in HttpContext.Current.Request.Form.AllKeys)
            {
                if (key != null)
                {
                    var match = regexId.Match(key);
                    if (match.Success)
                    {
                        var prevId = int.Parse(match.Groups["id"].Value);
                        int nextId;
                        int.TryParse(HttpContext.Current.Request.Form[string.Format("document_picker_{0}_ContentIdValue", prevId)], out nextId);

                        if (prevId == nextId)
                        {
                            continue;
                        }

                        if (nextId == 0)
                        {
                            // DELETE RELATION
                            var relations = Relation.GetRelations(prevId);
                            foreach (var relation in relations)
                            {
                                if (relation.Parent.Id == documentId || relation.Child.Id == documentId)
                                {
                                    relation.Delete();
                                }
                            }
                        }
                        else if (prevId == 0)
                        {
                            // ADD RELATION
                            Relation.MakeNew(documentId, nextId, RelationType.GetByAlias("relateDocumentOnCopy"), string.Empty);
                        }
                        else
                        {
                            // DELETE RELATION
                            var relations = Relation.GetRelations(prevId);
                            foreach (var relation in relations)
                            {
                                if (relation.Parent.Id == documentId || relation.Child.Id == documentId)
                                {
                                    relation.Delete();
                                }
                            }

                            // ADD RELATION
                            Relation.MakeNew(documentId, nextId, RelationType.GetByAlias("relateDocumentOnCopy"), string.Empty);
                        }
                    }
                }
            }
        }
        #endregion

        #region Methods

        /// <summary>
        /// The on init.
        /// </summary>
        /// <param name="e">
        /// The e.
        /// </param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.SuperSave();

            ContentTemplateContainer.Controls.Add(
                new LiteralControl(ResourceExtensions.GetRelatedDocuments(CurrentDocId, this.relationships)));

            this.AddResourceToClientDependency("Vizioz.Relationships.css.flags16.css", ClientDependencyType.Css);            
        }

        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            // Label
            this.pickerContainer = new Label { CssClass = "relationshipPicker" };

            // Content Picker
            this.contentPicker = new SimpleContentPicker();
            this.contentPicker.ID = this.contentPicker.ClientID;
            this.contentPicker.EnableViewState = false;
            
            this.pickerContainer.Controls.Add(this.contentPicker);

            ContentTemplateContainer.Controls.Add(this.pickerContainer);
        }

        #endregion
    }
}